package ua.kharkov.knure.dereza.summarytask4.i18n;

import java.io.IOException;

import org.apache.log4j.Logger;

import ua.kharkov.knure.dereza.summarytask4.core.Constants;
import ua.kharkov.knure.dereza.summarytask4.db.bean.ClientBean;

import javax.servlet.http.HttpSession;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;

/**
 * Custom tag for support i18n.
 * 
 * @author dereza
 * 
 */
public class I18nTag extends TagSupport {

	private static final long serialVersionUID = 6367039013550698410L;

	private static final Logger log = Logger.getLogger(I18nTag.class);

	private String locale;
	private String propertyKey;

	public void setPropertyKey(String propertyKey) {
		this.propertyKey = propertyKey;
	}

	public int doStartTag() throws JspException {
		JspWriter writer = pageContext.getOut();

		// gets locale from clientbean.
		HttpSession session = pageContext.getSession();
		ClientBean clientBean = (ClientBean) session.getAttribute("clientbean");

		// if clientbean == null, will be set default locale
		if (clientBean == null || clientBean.getLocale() == null) {
			session.setAttribute("locale", Constants.LOCALE_DEFAULT);
			log.debug("Was setuppped default locale --> "
					+ Constants.LOCALE_DEFAULT);
			locale = Constants.LOCALE_DEFAULT;
		} else {
			locale = clientBean.getLocale();
		}

		String message = ResourceManager.getMessage(propertyKey, locale);
		try {
			writer.print(message);
		} catch (IOException ex) {
			log.error("Cannot write message.", ex);
		}
		return SKIP_BODY;
	}

	public int doEndTag() {
		return EVAL_PAGE;
	}
}